package com.romotc.scache;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.romotc.common.http.CookieUtil;
import com.romotc.oschina.db.QueryHelper;
import com.romotc.qqrobot.bean.QQData;
import com.romotc.qqrobot.webqq.WebQQConstant;
import com.romotc.qqrobot.webqq.qqInterfaceCatching.QQUrlCatchingFactory;
import com.romotc.qqrobot.webqq.qqInterfaceCatching.QQUrlCatchingInterface;
import com.romotc.qqrobot.webqq.qqInterfaceLog.QQInterfaceLog;


public class RequestSpy extends request {

	/**
	 * 请求序号 累加
	 */
	private long reqSN = 0;
	private static long  reqSNCounter = 0;
	
//	static {
//		String sql = "select reqid, max(startTime) from osc_qq_datas;";
//		Integer maxReqId = QueryHelper.read(Integer.class, sql, null);
//		reqSNCounter = maxReqId;
//	}
	
	/**
	 * request的heads信息在请求结束之后会被改写，使用reqHead保存发送请求时的头信息
	 */
	private ArrayList<String> reqHeaders;
	
	
	/**
	 * 请求体
	 */
	private ArrayList<Byte> reqBody = new ArrayList<Byte>();
	private String reqBodyStr = null;
	
	/**
	 *服务器返回的消息体
	 */
	private ArrayList<Byte> resBody = new ArrayList<Byte>();
	private String resBodyStr;
	
	/**
	 * 请求开始时间
	 */
	private long reqStartTime;
	
	/**
	 * 请求结束时间
	 */
	private long reqEndTime;
	
	/**
	 * 服务器返回数据编码格式
	 */
	public String resCharSet = "utf-8";
	
	/**
	 * 记录日志的级别 方式
	 * 1000 - 1999记录数据库
	 */
	public int logLevel;
	/**
	 * 发送给服务器的请求数据
	 */
	private JSONObject reqInfos;
	
	private List<QQUrlCatchingInterface> catchingList;
	
	//记录到QQ通讯接口数据表中
	public static int LogType_2Db_QQInterfaceLog = 1001;
	
	private static ThreadGroup logThreads = new ThreadGroup("RequestSpy-Log");
	
	public RequestSpy(int htver, int met, String url, ArrayList<String> head,
			DataInputStream in, DataOutputStream out, int logLevel)
			throws MalformedURLException {
		//调用父类构造方法必须在第一行
		super(htver, met, url, head, in, out);
		
		//替换掉in 和 out
		super.in = new RequestSpyDataInputStreamWrap(in);
		super.out = new RequeestSpyDataOutPutStreamWrap(out);
		
		//发送请求时的请求信息
		reqHeaders = head;
		
		//生成请求序号
		this.reqSN = getReqSNCounter();
		
		//日志记录级别 && 方式
		this.logLevel = logLevel;
		if(this.URL.indexOf("http://d.web2.qq.com/channel/login") != -1)
			System.out.println();
		catchingList = QQUrlCatchingFactory.getCatingList(url);
	}

	
	private synchronized long getReqSNCounter() {
		return reqSNCounter++;
	}


	/**
	 * 请求开始时做下记录（发送请求头部信息）
	 */
	@Override
	public void raw_send_request(WebConnection wc) throws IOException {
		//记录请求开始时间
		reqStartTime = System.currentTimeMillis();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
		System.out.println("@# Start request [" + reqSN + "]" + httpreq.methodToString(method) + " "
				+ getURL() +  " @ " +fmt.format(new java.util.Date(reqStartTime)));
		
		super.raw_send_request(wc);
	}

	
	/**
	 * Post等非Get方式的请求发出
	 * 日后做请求拦截处理时重写
	 */
	@Override
	public void direct_request(boolean datafromclient) throws IOException {
		super.direct_request(datafromclient);
	}


	/**
	 * Get方式的请求发出
	 * 日后做请求拦截处理时重写
	 */
	@Override
	public void run_request(WebConnection wc) throws IOException {
		super.run_request(wc);
	}
	
	/**
	 * 在请求发出之前拦截
	 * @return 是否继续请求
	 */
	public boolean hackRequest() {
//		if(catchingList != null && !catchingList.isEmpty()) {
//			for(QQUrlCatchingInterface catching : catchingList) {
//				boolean goOn = catching.hackRequest(this);
//				if(!goOn)
//					return false;
//			}
//		}
		return true;
	}
	
	@Override
	/**
	 * 在请求响应之后拦截
	 */
	protected void callSpy(WebConnection wc) throws IOException{
//		System.out.println("RequestSpy.callSpy");
//		//对请求返回的结果进行加盐处理
//		if(catchingList != null && !catchingList.isEmpty()) {
//			for(QQUrlCatchingInterface catching : catchingList) {
//				boolean doNotGoOn = catching.modifyResponse(wc, this);
//				if(doNotGoOn)
//					break;
//			}
//		}
//		super.callSpy(wc);
	}
	
	
	
	/**
	 * 给浏览器发送请求响应头
	 * 增加对响应头的修改
	 */
	@Override
	public void send_headers() {
		// TODO Auto-generated method stub
//		if(catching != null) {
//			catching.modifyResHeaders(headers);
//		}
		super.send_headers();
	}
	
	/**
	 * 请求结束之后记录本次请求信息
	 */
	@Override
	public void transfer_object(WebConnection wc, OutputStream file,
			cachedir dir) throws IOException {
		//记录请求结束时间
		reqEndTime = System.currentTimeMillis();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
		System.out.println("@# End request [" + reqSN + "]" + getURL() +  " @ " + fmt.format(new java.util.Date(reqEndTime)));
		
		if(this.getURL().indexOf("http://s.web2.qq.com/api/get_user_friends2") != -1)
			System.out.println();
		super.transfer_object(wc, file, dir);
		
		
	}



	/**
	 * 
	 * @author romotc
	 *
	 */
	class RequestSpyDataInputStreamWrap extends DataInputStream {

		public RequestSpyDataInputStreamWrap(InputStream arg0) {
			super(new RequestSpyInputStreamWrap(arg0));
		}
		
	}
	class RequestSpyInputStreamWrap extends InputStream {
		private InputStream inputStream;
		
		public RequestSpyInputStreamWrap(InputStream origIs) {
			this.inputStream = origIs;
		}
		
		@Override
		public int read() throws IOException {
			int read = inputStream.read();
			reqBody.add((byte)read);
			return read;
		}

		/**
		 * 下面的方法也得覆盖！一个小坑耽误了1天时间。。 RomImportant
		 */
		@Override
		public int available() throws IOException {
			return inputStream.available();
		}

		@Override
		public void close() throws IOException {
			inputStream.close();
		}

		@Override
		public synchronized void mark(int readlimit) {
			inputStream.mark(readlimit);
		}

		@Override
		public boolean markSupported() {
			return inputStream.markSupported();
		}

		@Override
		public int read(byte[] b, int off, int len) throws IOException {
			int rt =  inputStream.read(b, off, len);
			
			if(rt > 0)
			for(int i = 0; i < rt; i++) {
				reqBody.add((byte)b[off + i]);
			}
			
			return rt;
		}

		@Override
		public int read(byte[] b) throws IOException {
			return read(b, 0, b.length);
		}

		@Override
		public synchronized void reset() throws IOException {
			inputStream.reset();
		}

		@Override
		public long skip(long n) throws IOException {
			return inputStream.skip(n);
		}
		
	}
	
	
	
	/**
	 * 
	 * @author romotc
	 *
	 */
	class RequeestSpyDataOutPutStreamWrap extends DataOutputStream {

		private OutputStream origOutputStream;
		public RequeestSpyDataOutPutStreamWrap(OutputStream arg0) {
			//第一行需要是调用父类构造方法 RomImportant
			super(new ReqeustSpyOutPutStreamWrap(arg0));
			this.origOutputStream = arg0;
		}
		public OutputStream getOrigOutputStream() {
			return origOutputStream;
		}
	}
	class ReqeustSpyOutPutStreamWrap extends OutputStream {
		private OutputStream outputStream;
		
		public ReqeustSpyOutPutStreamWrap(OutputStream orgiOs) {
			this.outputStream = orgiOs;
		}
		
		@Override
		public void write(int b) throws IOException {
			outputStream.write(b);
			resBody.add((byte)b);
			
		}

		/**
		 * 下面的方法也得覆盖！一个小坑耽误了1天时间。。 RomImportant
		 */
		@Override
		public void close() throws IOException {
			outputStream.close();
		}

		@Override
		public void flush() throws IOException {
			outputStream.flush();
		}

		@Override
		public void write(byte[] b, int off, int len) throws IOException {
			outputStream.write(b, off, len);
			for(int i = 0;i < len; i++) {
				resBody.add(b[off + i]);
			}
		}

		@Override
		public void write(byte[] b) throws IOException {
			write(b, 0, b.length);
		}
	}
	public long getReqSN() {
		return reqSN;
	}


	public ArrayList<String> getReqHeaders() {
		return reqHeaders;
	}

	/**
	 * 获取请求体
	 * @RomUnDo ctsize1 = -1时存在问题 Ptlogin2Check_Catching requestSpy.getReqInfoJson()中会存在阻塞
	 * @return
	 */
	public String getReqBody() {
		
		if(this.method == httpreq.REQUEST_GET)
			return null;
		
		String url = getURL();

		if(reqBodyStr != null)
			return reqBodyStr;
		
		if(getURL().indexOf("d.web2.qq.com/channel/send_buddy_msg2") != -1) {
			System.out.println();
		}
		if(this.reqBody == null || reqBody.size() < 1) {
			//为了使前置的请求拦截器能获取到请求体信息 这里需要提前取
			byte b[] = new byte[512];
			try {
				in.mark(4048);
				int len = -1;
				int ctsize1 = this.ctsize;
//				if(ctsize1 > 0)
					//下面是request中对应上面功能的代码
					while (ctsize1 != 0) {
						if (ctsize1 < 0)
							len = in.read(b);
						else
							len = in.read(b, 0, Math.min(ctsize1, 512));
						if (len == -1)
							break; /* konec dat! */
						ctsize1 -= len;
					}
					
					
					
				//使用request中的实现方式 自己的实现方式容易阻塞
//				while((len = in.read(b)) != -1)  {
//					//读的同时已经写到reqBody中了
//					if(getURL().indexOf("d.web2.qq.com/channel/send_buddy_msg2") != -1) {
//						System.out.println();
//					}
//					
//					//最后一次读取后再调用read会很慢
//					if(len < 512)
//						break;
//					
//				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
 				//将请求流重置
				in.reset();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			//上面已经把in中的数据读过了，为了以后处理中再次读取 这里重新生成一个
			if(this.reqBody != null && reqBody.size() > 0) {
//				Byte[] reqBodyArray = (Byte[])reqBody.toArray(new Byte[reqBody.size()]);
//				byte[] reqBodyarray = new byte[reqBodyArray.length];
////				System.arraycopy(reqBodyArray, 0, reqBodyarray, 0, reqBodyArray.length); 类型不对会报错
//				for(int i = 0;i < reqBodyArray.length;i++) {
//					reqBodyarray[i] = reqBodyArray[i];
//				}
//				this.in = new DataInputStream(new ByteArrayInputStream(reqBodyarray));
				
			}else {
				return null;
			}
		}
		
		byte[] reqBodyArray = new byte[reqBody.size()];
//		System.arraycopy(reqBody.toArray(), 0, reqBodyArray, 0, reqBody.size());
		int i = 0;
		for(Byte byte1 : reqBody) {
			reqBodyArray[i++] = (byte)byte1;
		}
		
		//获取请求头部的编码格式
		
		try {
			//RomUnDo 这里utf-8应该从请求头获取
			reqBodyStr = new String(reqBodyArray, "utf-8");
//			URLDecoder decoder = new URLDecoder();
//			reqBodyStr = decoder.decode(reqBodyStr, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return reqBodyStr;
	}

	@Override
	public void read_headers(String firstline, WebConnection wc)
			throws IOException {
		super.read_headers(firstline, wc);
		
		//获取服务器返回的编码格式
		if(ctype != null) {
			//Content-Type: application/x-javascript; charset=gb2312
			//Content-Type: text/plain; charset=utf-8
			//Content-Type: application/json;charset=utf-8
			//Content-Type: text/html
			//text/plain; charset=utf-8
			Pattern pattern = Pattern.compile("charset=([a-z|A-Z|0-9|-|\\-]+)");
			Matcher matcher = pattern.matcher(ctype);
			if(matcher.find())
			{
				resCharSet = matcher.group(1);
			}
		}
	}


	public String getResBody() {
		if(resBodyStr != null)
			return resBodyStr;
		
		if(this.resBody == null || resBody.size() < 1) 
			return null;
		
		byte[] resBodyArray = new byte[resBody.size()];
//		System.arraycopy(resBody.toArray(), 0, resBodyArray, 0, resBody.size());
		int i = 0;
		for(Byte byte1 : resBody) {
			resBodyArray[i++] = (byte)byte1;
		}
		
		//解析压缩数据
		if("gzip".equals(encoding)) {
			ByteArrayInputStream bis = new ByteArrayInputStream(resBodyArray);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try {
				GZIPInputStream gis = new GZIPInputStream(bis);
			    int count;   
			    byte data[] = new byte[512];   
			    while ((count = gis.read(data, 0, 512)) != -1) {   
			    	bos.write(data, 0, count);   
			    }   
			  
			    gis.close(); 
			    resBodyArray = bos.toByteArray();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		try {
			resBodyStr = new String(resBodyArray, resCharSet);
			
			//Just for Test
			System.out.println(resBodyStr);
			
//			URLDecoder decoder = new URLDecoder();
//			reqBodyStr = decoder.decode(resBodyArray, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return resBodyStr;
	}


	public long getReqStartTime() {
		return reqStartTime;
	}


	public long getReqEndTime() {
		return reqEndTime;
	}


	/**
	 * 请求响应结束之后记录本次请求信息
	 */
	public void logMe() {
		if(this.LogType_2Db_QQInterfaceLog == this.logLevel && !WebQQConstant.isUi(this.getURL())
				|| (this.logLevel == 1 && WebQQConstant.isContents(this.ctype))) {
			if(this.getURL().indexOf(QQData.URL_SEND_BUDDY_MSG2) != -1) {
				System.out.println("LogMe...");
			}
			new Thread(logThreads, new QQInterfaceLog(this)).start();
		}
	}

	
	/**
	 * 发送给服务器的请求信息
	 * 包含request.params && Post的数据
	 * @return
	 */
	public JSONObject getReqInfoParamJson() {
		JSONObject reqInfos;
		
		//Url中的数据
		int idx = getURL().indexOf("?");
		reqInfos = new JSONObject();
		
		StringTokenizer token = null;
		String tokenStr = null;
		int idx1;
		String key = null;
		String value = null;
		
		if(idx != -1) {
			String urlParamStr = getURL().substring(idx + 1);
			token = new StringTokenizer(urlParamStr, "&");
			while(token.hasMoreTokens()) {
				tokenStr = token.nextToken();
				if(tokenStr == null)
					continue;
				
				idx1 = tokenStr.indexOf("=");
				if(idx1 == -1) {
					key = tokenStr;
					value = null;
				} else {
					key = tokenStr.substring(0, idx1);
					value = tokenStr.substring(idx1 + 1);
				}
				
				try {
					reqInfos.put(key, value);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
		return reqInfos;
	}
	
	/**
	 * 发送给服务器的请求信息
	 * 包含request.params && Post的数据
	 * @return
	 */
	public JSONObject getReqInfoJson() {
		if(reqInfos != null) {
			return reqInfos;
		}
		
		//Url中的数据
		int idx = getURL().indexOf("?");
		reqInfos = new JSONObject();
		
		StringTokenizer token = null;
		String tokenStr = null;
		int idx1;
		String key = null;
		String value = null;
		
		if(idx != -1) {
			String urlParamStr = getURL().substring(idx + 1);
			token = new StringTokenizer(urlParamStr, "&");
			while(token.hasMoreTokens()) {
				tokenStr = token.nextToken();
				if(tokenStr == null)
					continue;
				
				idx1 = tokenStr.indexOf("=");
				if(idx1 == -1) {
					key = tokenStr;
					value = null;
				} else {
					key = tokenStr.substring(0, idx1);
					value = tokenStr.substring(idx1 + 1);
				}
				
				try {
					reqInfos.put(key, value);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
		//请求体中的数据  只有post才有请求体信息
		String reqBodyStr = this.method == httpreq.REQUEST_POST ? getReqBody() : null;
		if(reqBodyStr != null) {
			token = new StringTokenizer(reqBodyStr, "&");
			while(token.hasMoreTokens()) {
				tokenStr = token.nextToken();
				if(tokenStr == null)
					continue;
				
				idx1 = tokenStr.indexOf("=");
				if(idx1 == -1) {
					key = tokenStr;
					value = null;
				} else {
					key = tokenStr.substring(0, idx1);
					value = tokenStr.substring(idx1 + 1);
				}
				
				try {
					reqInfos.put(key, value);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
		return reqInfos;
	}

	/**
	 * 将请求信息转换为json格式字符串
	 * Get:请求连接中的信息
	 * Post:请求体中的信息
	 * @return
	 */
	public String getReqInfos() {
		return getReqInfoJson().toString();
	}


	private JSONObject reqCookies;
	/**
	 * 请求发出时的cookies
	 * @return
	 */
	public JSONObject getReqCookiesJson() {
		if(reqCookies != null) {
			return reqCookies;
		}

		reqCookies = new JSONObject();
		for(String header : this.getReqHeaders()) {
			if(header.startsWith("Cookie:")) {
				header = header.substring(7);
				StringTokenizer tokenizer = new StringTokenizer(header, ";");
				String cookieLine;
				int idx = -1;
				String cookieKey;
				String cookieValue;
				while(tokenizer.hasMoreTokens()) {
					cookieLine = tokenizer.nextToken();
					idx = cookieLine.indexOf("=");
					if(idx == -1)
						continue;
					cookieKey = cookieLine.substring(0, idx).trim();
					cookieValue = cookieLine.substring(idx + 1);
					try {
						reqCookies.put(cookieKey, cookieValue);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		return reqCookies;
	}

	private String cookieStr = null;
	public String getReqCookiesStr() {
		if(cookieStr != null) {
			return cookieStr;
		}
		for(String header : this.getReqHeaders()) {
			if(header.startsWith("Cookie:")) {
				cookieStr = header.substring(7);
				return cookieStr;
				
			}
		}
		
		cookieStr = "";
		return cookieStr;
	}

	/**
	 * 服务器返回的cookie信息
pt2gguin=o1586030808; EXPIRES=Fri, 02-Jan-2020 00:00:00 GMT; PATH=/; DOMAIN=qq.com;
uin=o1586030808; PATH=/; DOMAIN=qq.com;
skey=@Jf2uW5KKq; PATH=/; DOMAIN=qq.com;
clientuin=; EXPIRES=Fri, 02-Jan-1970 00:00:00 GMT; PATH=/; DOMAIN=qq.com;
clientkey=; EXPIRES=Fri, 02-Jan-1970 00:00:00 GMT; PATH=/; DOMAIN=qq.com;
zzpaneluin=; EXPIRES=Fri, 02-Jan-1970 00:00:00 GMT; PATH=/; DOMAIN=qq.com;
zzpanelkey=; EXPIRES=Fri, 02-Jan-1970 00:00:00 GMT; PATH=/; DOMAIN=qq.com;
ptisp=cnc; PATH=/; DOMAIN=qq.com;
ptuserinfo=6f70656e646576; PATH=/; DOMAIN=ptlogin2.qq.com;
show_id=; PATH=/; DOMAIN=qq.com;
ptcz=3ca1cb3e9f8d65901eb80d5c018e02ac7e3ceb563f64f0f7f59d8b9c948b8691; EXPIRES=Fri, 02-Jan-2020 00:00:00 GMT; PATH=/; DOMAIN=ptlogin2.qq.com;
airkey=; EXPIRES=Fri, 02-Jan-1970 00:00:00 GMT; PATH=/; DOMAIN=qq.com;
ptwebqq=c3385fe2553ce164041d23e9b6fb6fa6b54fb04cdcab1e67f556ace9d558a449; PATH=/; DOMAIN=qq.com;
	 * @return
	 */
	public JSONObject getResCookiesJson(JSONObject cookieObj) {
		if(headers == null || headers.isEmpty())
			return null;
		
		for(String header : headers) {
			//Set-Cookie:verifysession=h00fb49c819ec8a3130d523d3b53704a9eabad45cadac42bf4fecb1d7c9d95d918b40e15d2f77d3881a; PATH=/; DOMAIN=qq.com;
			
			//多个cookie以, 分割
			//Set-Cookie:
			//ptvfsession=c9fd16a04882d9810505444b5ac83168724be0bc323fe1cc5ebaa2af5306e0253d776e319d59b1efa21e111e7712428b; PATH=/; DOMAIN=ptlogin2.qq.com;
			//, 
			//confirmuin=97190865; PATH=/; DOMAIN=ptlogin2.qq.com;
			if(header.startsWith("Set-Cookie:")) {
				header = header.substring("Set-Cookie:".length());
				cookieObj = CookieUtil.buildCookieJsonObjFromResHeader(header, cookieObj);
			}
		}
		
		return cookieObj;
	}
	
	public JSONObject getResCookiesJson() {
		return getResCookiesJson(null);
	}

public static void main(String[] args) throws Exception{
	String header = "login_param=target%3Dself%26style%3D5%26mibao_css%3Dm_webqq%26appid%3D1003903%26enable_qlogin%3D0%26no_verifyimg%3D1%26s_url%3Dhttp%253A%252F%252Fweb.qq.com%252Floginproxy.html%26f_url%3Dloginerroralert%26strong_login%3D1%26login_state%3D10%26t%3D20120320001; PATH=/; DOMAIN=ui.ptlogin2.qq.com;, uikey=b4b878de329c654d79cb8f63c42214926a7b3d670500cd26d326ab22af684aa7; PATH=/; DOMAIN=ptlogin2.qq.com;";
	JSONObject cookie = CookieUtil.buildCookieJsonObjFromResHeader(header);
	Iterator<String> iterator = cookie.keys();
	while(iterator.hasNext()) {
		String key = iterator.next();
		String value = cookie.getString(key);
		System.out.println(key + ":" + value);
	}
}


	public static JSONObject parseCookieJsonFromStr(String cookieStr) {
		return CookieUtil.parseCookieJsonFromStr(cookieStr);
	}


	public static String parseCookieJsonToStr(JSONObject cookie) {
		return CookieUtil.parseCookieJsonToStr(cookie);
	}
	
	/**
	 * 读取输入流
	 */
	public void readRequestInfo() {
		if (method == httpreq.REQUEST_POST) {
			byte b[] = new byte[512];
			int rb;
			if (ctsize < 0)
				keepalive = false; // disable INPUT keepalive
			// System.out.println("[DEBUG] Need to read "+ctsize+" bytes
			// from client");
			try {
				in.mark(4086);
				while (ctsize != 0) {
					if (ctsize < 0)
						rb = in.read(b);
					else
						rb = in.read(b, 0, Math.min(ctsize, 512));
					if (rb == -1)
						break; /* konec dat! */
					ctsize -= rb;
				}
				in.reset();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		
	}	
}
